package gpstools.data;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class XMLUtils {

	private static DatatypeFactory datatypeFactory;

	/**
	 * Creates XMLGregorianCalendar object
	 * 
	 * @param time
	 *            time in milliseconds
	 * @return XMLGregorianCalendar for given time
	 */
	public static XMLGregorianCalendar toXMLGregorianCalendar(long time) {
		GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
		calendar.setTime(new Date(time));
		return getDatatypeFactory().newXMLGregorianCalendar(calendar);
	}

	public static XMLGregorianCalendar toXMLGregorianCalendar(String value) {
	    return getDatatypeFactory().newXMLGregorianCalendar(value);
	}

	private static DatatypeFactory getDatatypeFactory() {
		if (datatypeFactory == null) {
			try {
				datatypeFactory = DatatypeFactory.newInstance();
			} catch (DatatypeConfigurationException e) {
				throw new RuntimeException(e);
			}
		}
		return datatypeFactory;
	}

}
